﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace STHPMS1.Common.C_Utils
{
    public static class QueryHelper
    {
        public static Expression<Func<T, bool>> CreateCriteria<T>(Expression<Func<T>> selector)
        {
            var memberInit = selector.Body as MemberInitExpression;
            if (memberInit == null)
                throw new InvalidOperationException("MemberInitExpression is expected");
            var p = Expression.Parameter(typeof(T), "x");

            Expression body = null;
            foreach (MemberAssignment binding in memberInit.Bindings)
            {
                string propertyName = binding.Member.Name;
                object propertyValue;
                if (binding.Expression.NodeType == ExpressionType.Constant)
                {
                    propertyValue = (binding.Expression as ConstantExpression).Value;
                }
                else
                {
                    propertyValue = Expression.Lambda(binding.Expression, null).Compile().DynamicInvoke();
                }

                if (propertyValue == null) continue;

                var comparer = Expression.Equal(
                    Expression.MakeMemberAccess(p, binding.Member),
                    binding.Expression);
                body = body == null ? comparer : Expression.AndAlso(body, comparer);
            }
            if (body == null) return null;
            //if (body == null) body = Expression.Constant(true);

            return Expression.Lambda<Func<T, bool>>(body, p);
        }

    }
}
